package com.stu.utils;

import java.util.HashMap;
import java.util.Map;

import net.minidev.json.JSONObject;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.Payload;
import com.nimbusds.jose.crypto.MACSigner;
import com.stu.entity.permission.User;
import com.stu.entity.service.TechnologyBlog;
/**************************************************
 * 注册方法： 
 * 		用户注册的时候注册到本系统的同时注册到 多说  使用 import
 * 
 * 登录回调方法：（这个方法写到 login 回调）
 *     	这里获取 code ,	通过code 和 client_id(short_name) 获取 access_token  post //  http://api.duoshuo.com/oauth2/access_token
 *      使用 user_id 和 access_token 获取 用户多说信息   get // http://api.duoshuo.com/users/profile.json?user_id=378333
 *      判断是不是注册了本系统，如果没有注册，注册到本系统，将本系统的信息和多说信息 合并同步到多说 join 方法
 *     	如果注册了本系统，登录该账号 
 * 退出回调方法：
 * 		退出本系统账号
 * 我的登录：
 *  	var u=new CookieUtils(); 
 *  	u.setCookie("duoshuo_token",cookieVal);
 * 我的退出
 * 		u.delCookie("duoshuo_token");
 * 
 ***************************************************/
/**
 * 多说 帮助类
 * @author Administrator
 *
 */
public class DuoShuoUtils implements LoggerUtils{
	
	/**
	 * 在多说注册的二级域名
	 */
	static String DUOSHUO_SHORTNAME = "lizi2";
	/**
	 * 密钥
	 */
	static String DUOSHUO_SECRET = "6010048695604a0bd409a0403ab2e941";
	
	/**
	 * 根据用户信息生成token，用来保存到Cookie中
	 * @param shortName 多说二级域名
	 * @param userId 本系统用户id
	 * @param nickname 本系统用户昵称（可选）
	 * @return
	 */
	public static String getToken(String userId,String nickname){
		try {
			JSONObject userInfo = new JSONObject();
	        
	        userInfo.put("short_name", DUOSHUO_SHORTNAME);//必须项
	        userInfo.put("user_key", userId);//必须项
	        if(StringUtils.isNotEmpty(nickname)){
	        	userInfo.put("name", nickname);//可选项 
	        }
	        Payload payload = new Payload(userInfo);
	        JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);
	        header.setContentType("jwt");
	        // Create JWS object
	        JWSObject jwsObject = new JWSObject(header, payload);
	        // Create HMAC signer        
	        JWSSigner signer = new MACSigner(DUOSHUO_SECRET.getBytes());
	        try {
	                jwsObject.sign(signer);

	        } catch (JOSEException e) {
	        		logger.error(e);
	                System.err.println("Couldn't sign JWS object: " + e.getMessage());
	                return null;
	        }        
	        // Serialise JWS object to compact format
	        return jwsObject.serialize();
		} catch (Exception e) {
			logger.error(e);
			System.err.println(e.getMessage());
		}
		return null;
	}

	/**
	 * 
	 * @author lijian
	 *
	 * @param accessToken
	 * @param user 本系统用户
	 * @return
	 */
	public static String join(String accessToken,User user){
		try {
			Map<String,String>map=new HashMap<String,String>();
			map.put("short_name",DUOSHUO_SHORTNAME);
			map.put("secret", DUOSHUO_SECRET);
			map.put("access_token", accessToken);
			
			map.put("user[user_key]", user.getUuid());
			map.put("user[name]", user.getNickname());
			map.put("user[avatar_url]", user.getAvatar_url());
			map.put("user[url]", user.getUrl());
			map.put("user[email]", user.getEmail());
			map.put("user[created_at]", user.getCreateTime().toString());
			
			return HttpUtils.sendPost("http://api.duoshuo.com/sites/join.json", HttpUtils.combineParams(map));
		} catch (Exception e) {
			logger.error(e);
			System.err.println(e.getMessage());
		}
		return null;
	}
	
	/**
	 * 获取多说用户的详细信息
	 * @param duoShuoUserId 注意这里是多说的用户id，不是本系统的用户id
	 * @return
	 */
	public static String profile(String duoShuoUserId){
		try {
			Map<String,String>map=new HashMap<String,String>();
			map.put("user_id", duoShuoUserId);
			return HttpUtils.sendGet("http://api.duoshuo.com/users/profile.json",HttpUtils.combineParams(map));
		} catch (Exception e) {
			logger.error(e);
			System.err.println(e.getMessage());
		}
		return null;
	}
	
	/**
	 * 将用户导入到多说
	 * @author lijian
	 *
	 * @return
	 */
	public static String importUser(User user){
		try {
			Map<String,String>map=new HashMap<String,String>();
			map.put("short_name",DUOSHUO_SHORTNAME);
			map.put("secret", DUOSHUO_SECRET);
			
			map.put("users[0][user_key]", user.getUuid());
			map.put("users[0][name]", user.getNickname());
			map.put("user[0][avatar_url]", user.getAvatar_url());
			map.put("user[0][url]", user.getUrl());
			map.put("user[0][email]", user.getEmail()); 
			map.put("user[0][created_at]", user.getCreateTime().toString());
			
			String result = HttpUtils.sendPost("http://api.duoshuo.com/users/import.json",HttpUtils.combineParams(map));
			//{"access_token":"4c51d2f73fd6bc8a1cd8fcf8f5f2bba9","expires_in":7776000,"user_id":"6220235252414022402","user_key":"123","remind_in":7689623,"code":0}
//			JSONArray jsonArray=JSONArray.fromObject("["+result+"]");
//			net.sf.json.JSONObject j=jsonArray.getJSONObject(0);
//			if(j.get("code").equals(0)){
//				
//			}
			return result;
		} catch (Exception e) {
			logger.error(e);
			System.err.println(e.getMessage());
		}
		return null;
	}
	
	
	/**
	 * 将用户导入到多说
	 * @author lijian
	 *
	 * @return
	 */
	public static String importThread(TechnologyBlog blog){
		try {
			Map<String,String>map=new HashMap<String,String>();
			map.put("short_name",DUOSHUO_SHORTNAME);
			map.put("secret", DUOSHUO_SECRET);
			
			/*
			 	$.post('http://api.duoshuo.com/threads/import.json', {
				"short_name":"lizi2",
				"secret":"6010048695604a0bd409a0403ab2e941",
				"threads[0][thread_key]":"${blog.uuid}",
				"threads[0][title]":"${blog.title}",
				"threads[0][url]":"<%=basePath%>/blog_getById.action?id=${blog.uuid}"
			 
			 */
			
			map.put("threads[0][thread_key]", blog.getUuid());
			map.put("threads[0][title]", blog.getTitle());
			map.put("threads[0][url]", "127.0.0.1:8080/geek/blog_getById.action?id="+blog.getUuid());
			
			String result = HttpUtils.sendPost("http://api.duoshuo.com/threads/import.json",HttpUtils.combineParams(map));
			return result;
		} catch (Exception e) {
			logger.error(e);
			System.err.println(e.getMessage());
		}
		return null;
	}
	
	/**
	 * 获取 Access_Token 
	 * @param code 登录返回的code
	 * @return
	 */
	public static String getAccessToken(String code){
		try {
			Map<String,String>map=new HashMap<String,String>();
			map.put("client_id", DUOSHUO_SHORTNAME);//注意这里的client_id 就是 short_name
			map.put("code", code);
			return HttpUtils.sendPost("http://api.duoshuo.com/oauth2/access_token", HttpUtils.combineParams(map));
		} catch (Exception e) {
			logger.error(e);
			System.err.println(e.getMessage());
		}
		return null;
	}
	public static void main(String [] args){
//        System.out.println(getToken(DUOSHUO_SHORTNAME, "123", "网站用户A"));
//		System.out.println(profile("6245040770399601410"));
//		System.out.println(importUser(new User()));
		System.out.println(profile("cf781471c2e785b90d821995a1ace753"));
        //示例输出结果为eyJhbGciOiJIUzI1NiIsImN0eSI6Imp3dCJ9.eyJ1c2VyX2tleSI6IjEiLCJuYW1lIjoi572R56uZ55So5oi3QSIsInNob3J0X25hbWUiOiJ0ZXN0In0.NXKDXwXThzFkyfl_k_-p6mfM5cpOFppvfdIjrjEq14I
        //eyJhbGciOiJIUzI1NiIsImN0eSI6Imp3dCJ9.eyJ1c2VyX2tleSI6IjEyMyIsIm5hbWUiOiLnvZHnq5nnlKjmiLdBIiwic2hvcnRfbmFtZSI6ImxpemkyIn0.ciJeMhSNqt6gbr97g8JHlf7qJqKhT_3FRnQdQIEv9VE
	}
}
